package com.cameron.serviceedu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cameron.entity.CourseVo;
import com.cameron.servicebase.config.exception.BusinessException;
import com.cameron.entity.EduCourseCollect;
import com.cameron.serviceedu.entity.viewobject.CollectVo;
import com.cameron.serviceedu.service.EduCourseCollectService;
import com.cameron.serviceedu.service.EduCourseService;
import com.cameron.utils.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.cameron.constant.CollectCourseConstant.COLLECT_KEY_PREFIX;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/01/12/11:30
 */
@Api("收藏控制器")
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/service/edu-collect")
public class EduCollectController {

    @Resource
    private EduCourseCollectService eduCourseCollectService;

    @Resource
    private EduCourseService eduCourseService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 收藏或取消收藏功能
     */

    @PostMapping("/collectOrUncollected")
    public Result collect(@RequestBody CollectVo collectVo) {
        EduCourseCollect courseCollect = new EduCourseCollect();
        String courseId = collectVo.getCourseId();
        String userId = collectVo.getUserId();
        //判空
        if (StringUtils.isAnyBlank(courseId, userId))
            throw new BusinessException(40000, "参数为空");
        //判断该用户是否收藏过该课程
        boolean isCollected = eduCourseCollectService.isCollected(collectVo);
        if (isCollected) {
            redisTemplate.opsForSet().remove(COLLECT_KEY_PREFIX + courseId, userId);
            eduCourseCollectService.removeByCollectVo(collectVo);
            return Result.ok().message("取消收藏成功！").data("isCollect", 0);
        }
        courseCollect.setCourseId(courseId);
        courseCollect.setMemberId(userId);
        courseCollect.setGmtCreate(new Date());
        courseCollect.setGmtModified(new Date());
        eduCourseCollectService.save(courseCollect);
        return Result.ok().message("收藏成功!").data("isCollect", 1);
    }

    @GetMapping("collect/state")
    public Result getCollectState(CollectVo collectVo) {
        String courseId = collectVo.getCourseId();
        String userId = collectVo.getUserId();
        if (StringUtils.isAnyBlank(courseId, userId)) {
            log.info("courseId:{}\nuserId:{}", courseId, userId);
            throw new BusinessException(40001, "参数错误");
        }
        boolean collected = eduCourseCollectService.isCollected(collectVo);
        return Result.ok().data("state", collected ? 1 : 0);
    }

    @GetMapping("collectList/{memberId}")
    public List<CourseVo> getCollectListByMemberId(@PathVariable String memberId) {
        LambdaQueryWrapper<EduCourseCollect> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduCourseCollect::getMemberId, memberId);
        //获取该用户的收藏课程
        List<EduCourseCollect> collectList = eduCourseCollectService.list(wrapper);
        //若该用户没有收藏任何课程，则返回空集合
        if (CollectionUtils.isEmpty(collectList)) return Collections.emptyList();
        //将id收集起来
        ArrayList<String> courseIds = collectList
                .stream().map(EduCourseCollect::getCourseId)
                .collect(Collectors.toCollection(ArrayList::new));
        //使用多个id查询 并转为vo返回
        return eduCourseService.listByIds(courseIds)
                .stream().map(course -> {
                    CourseVo courseVo = new CourseVo();
                    courseVo.setCourseId(course.getId());
                    courseVo.setTitle(course.getTitle());
                    courseVo.setPrice(course.getPrice());
                    courseVo.setCover(course.getCover());
                    return courseVo;
                }).limit(4).collect(Collectors.toList());
    }
}
